//
//  DLMainViewVC.m
//  DontRem
//
//  Created by apple on 2021/1/15.
//

#import "DLMainViewVC.h"
#import "DLAddPswVC.h"
#import "DLGroupModel.h"
#import "DLMainViewRecordCell.h"
#import "DLMainDrawView.h"
#import <BRPickerView/BRPickerView.h>
@interface DLMainViewVC ()
@property(nonatomic,assign)int page;
@property(nonatomic,retain)NSMutableArray * dataArr;
@property(nonatomic,retain)QMUIButton * centerBtn;
@end

@implementation DLMainViewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor normalColor:UnderLineColor darkColor:UIColorBlack];
    self.myTitle = @"首页";
    self.dataArr = [NSMutableArray new];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSelf) name:DeleteOrEditGroupNotification object:nil];
    [self createCenterBtn];
    MJWeakSelf
    self.myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 0;
        [weakSelf.dataArr removeAllObjects];
        [weakSelf getData:nil];
    }];
    self.myTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf getData:nil];
    }];
    [self getData:nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM DLPswRecordTab WHERE BG_title LIKE '%%%@%%' OR BG_groupName LIKE '%%%@%%' OR BG_account LIKE '%%%@%%'",textField.text,textField.text,textField.text];
    NSArray * arr = bg_executeSql(sql, DLPswRecordTab, [DLPswModel class]);
    if (_dataArr.count!=0) {
        [_dataArr removeAllObjects];
    }
    [self.view endEditing:YES];
    [_dataArr addObjectsFromArray:arr];
    [self.myTab reloadData];
    return YES;
}
-(void)centerBtnClick{
    NSArray* groups = [DLGroupModel bg_findAll:DLGroupTab];
    NSMutableArray * arr = [NSMutableArray new];
    [arr addObject:@"全部"];
    for (DLGroupModel * mo  in groups) {
        [arr addObject:mo.groupName];
    }
    [BRStringPickerView showPickerWithTitle:@"选择分组" dataSourceArr:arr selectIndex:0 resultBlock:^(BRResultModel * _Nullable resultModel) {
        [self.dataArr removeAllObjects];
        if (resultModel.index == 0) {
            [self.centerBtn setTitle:@"全部" forState:UIControlStateNormal];
            self.centerBtn.mm_sizeToFit().mm_center().mm_top(kStatusBarHeight).mm_width(self.centerBtn.mm_w + 20).mm_height(kNavBarHeight);
            [self getData:nil];
        }else{
            DLGroupModel * mo = groups[resultModel.index-1];
            [self.centerBtn setTitle:mo.groupName forState:UIControlStateNormal];
            self.centerBtn.mm_sizeToFit().mm_center().mm_top(kStatusBarHeight).mm_width(self.centerBtn.mm_w + 20).mm_height(kNavBarHeight);
            [self getData:mo.bg_id];
        }
        
    }];
}
-(void)createCenterBtn{
    self.centerBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [self.centerBtn setTitle:@"全部" forState:UIControlStateNormal];
    self.centerBtn.titleLabel.font = UIFontMake(floor(AUTO(17)));
    [self.centerBtn setTitleColor:TextColor forState:UIControlStateNormal];
    [self.centerBtn setImagePosition:QMUIButtonImagePositionRight];
    [self.centerBtn setImage:Image(@"down") forState:UIControlStateNormal];
    [self.centerBtn addTarget:self action:@selector(centerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.centerBtn.spacingBetweenImageAndTitle = 6;
    [self.baseNavView addSubview:self.centerBtn];
    self.centerBtn.mm_sizeToFit().mm_center().mm_top(kStatusBarHeight).mm_width(self.centerBtn.mm_w + 20).mm_height(kNavBarHeight);
}
-(void)reloadSelf{
    [self.dataArr removeAllObjects];
    [self getData:nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DLMainViewRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[DLMainViewRecordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if (indexPath.row < self.dataArr.count) {
        cell.model = self.dataArr[indexPath.row];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.dataArr.count) {
        DLPswModel * mo = self.dataArr[indexPath.row];
        CGFloat hei = [tableView cellHeightForIndexPath:indexPath model:mo keyPath:@"model" cellClass:[DLMainViewRecordCell class] contentViewWidth:SCREEN_WIDTH];
        return ceilf(hei);
    }
    return 45;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.dataArr.count) {
        DLPswModel * mo = self.dataArr[indexPath.row];
        DLAddPswVC * vc = [DLAddPswVC new];
        vc.model = mo;
        vc.reloadBlock = ^{
            [self.myTab.mj_header beginRefreshing];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return KTabbarSafeBottomMargin;
}
-(void)navLeftBtnClick{
    DLMainDrawView * drawView = [[DLMainDrawView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:drawView];
}

- (void)navRightBtnClick{
    DLAddPswVC * vc = [DLAddPswVC new];
    vc.reloadBlock = ^{
        [self.myTab.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    BOOL isFirstOpen = [DLUserDefaultModel userDefaultsModel].firstOpen;
    if (isFirstOpen) {
        [DLUserDefaultModel userDefaultsModel].firstOpen = NO;
        DLGroupModel * mo = [DLGroupModel new];
        mo.groupName = @"默认分组";
        mo.bg_tableName = DLGroupTab;
        [mo bg_save];
    }    
}
-(void)getData:(NSNumber * _Nullable )group_id{
    NSArray * arr = nil;
    if (group_id) {
        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"group_bg_id"),bg_sqlValue(group_id)];
        arr = [DLPswModel bg_find:DLPswRecordTab where:where];
    }else{
        arr = [DLPswModel bg_find:DLPswRecordTab range:NSMakeRange(_page*50+1,50) orderBy:nil desc:YES];
    }
    [self.dataArr addObjectsFromArray:arr];
    [Mytools NeedResetNoViewWithTable:self.myTab andArr:self.dataArr];
    [self.myTab.mj_header endRefreshing];
    [self.myTab.mj_footer endRefreshing];
    [self.myTab reloadData];
}
#pragma mark 父类方法
-(void)beginInput{
//    NSLog(@"开始输入");
}
-(void)cancelInput{
//    NSLog(@"点了取消");
    self.inputTF.text = @"";
    [self.dataArr removeAllObjects];
    [self getData:nil];
}
-(void)cancelInputAniEnd{
//    NSLog(@"取消动画结束");
}

- (void)textFieldDidChangeValue:(UITextField*)textField{
    UITextRange * selectRange = [textField markedTextRange];
    NSString * newText = [textField textInRange:selectRange];
    if (newText.length > 0) {
        return;
    }
//    NSLog(@"%@",textField.text);
}
@end
